<?php

if (! function_exists('is_linux')) {
    /**
     * is_linux
     * @return bool
     */
    function is_linux():bool
    {
        return strpos(PHP_OS,"Linux")!==false;
    }
}

if (! function_exists('bash_exec')) {
    /**
     * bash_exec
     * @param $cmd
     * @return array|false
     */
    function bash_exec($cmd)
    {
        if(empty($cmd))
            return false;
        return Swoole\Coroutine\System::exec($cmd);
    }
}

if (! function_exists('exception_format')) {
    /**
     * exception_format
     * @param Throwable $exception
     * @param bool      $log
     * @return array|void
     */
    function exception_format(Throwable $exception, $log=true)
    {
        $exceptionArray = [
            'code'        => $exception->getCode(),
            'file'        => $exception->getFile(),
            'line'        => $exception->getLine(),
            'message'     => $exception->getMessage(),
            'traceString' => $exception->getTraceAsString(),
            // 'trace'       => $exception->getTrace(),
        ];

        $log && \app\service\Log::error('Exception',$exceptionArray);

        if(!$log)
            return $exceptionArray;
    }
}

if (! function_exists('print_ln')) {
    /**
     * print_ln
     * @param $expression
     * @param false $return
     */
    function print_ln($expression, $return = false)
    {
        print_r($expression, $return);
        print_r(PHP_EOL);
    }
}

if (! function_exists('print_success')) {
    /**
     * print_success
     * @param $expression
     */
    function print_success($expression)
    {
        print_ln("\033[0m\033[32m". print_r($expression,1) . "\033[0m" );
    }
}

if (! function_exists('print_error')) {
    /**
     * print_error
     * @param $expression
     */
    function print_error($expression)
    {
        print_ln("\033[0m\033[31m". print_r($expression,1) . "\033[0m" );
    }
}

if (! function_exists('get_dir_files_content')) {
    /**
     * get_dir_files_content
     * @param string $dir
     */
    function get_dir_files_content($dir)
    {
        $fileList = [];
        if(is_file($dir)){
            $fileList[] = [
                'name' => basename($dir),
                'path' => $dir,
                'content' => file_get_contents($dir),
            ];
        }elseif (is_dir($dir)){
            if ($handle = opendir($dir)) {
                while (false !== ($file = readdir($handle))) {
                    if($file=='..' || $file=='.'){
                        continue;
                    }
                    $filePath = $dir.DIRECTORY_SEPARATOR.$file;
                    if(is_file($filePath)) {
                        $fileList[] = [
                            'name' => basename($filePath),
                            'path' => $filePath,
                            'content' => file_get_contents($filePath),
                        ];
                    }
                }
                closedir($handle);
            }
        }
        return $fileList;
    }
}

if (! function_exists('encrypt')) {
    /**
     * encrypt
     * @param string $string
     * @param string $operation
     * @param string $key
     * @return string
     */
    function encrypt(string $string,string $operation,string $key = '')
    {
        $key           = md5($key);
        $key_length    = strlen($key);
        $string        = $operation == 'D' ? base64_decode($string) : substr(md5($string . $key), 0, 8) . $string;
        $string_length = strlen($string);

        $randomKey = $box = [];

        $result = '';

        for ($i = 0; $i <= 255; $i++) {
            $randomKey[$i] = ord($key[$i % $key_length]);
            $box[$i]    = $i;
        }

        for ($j = $i = 0; $i < 256; $i++) {
            $j       = ($j + $box[$i] + $randomKey[$i]) % 256;
            $tmp     = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }

        for ($a = $j = $i = 0; $i < $string_length; $i++) {
            $a       = ($a + 1) % 256;
            $j       = ($j + $box[$a]) % 256;
            $tmp     = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result  .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }

        if ($operation == 'D') {
            if (substr($result, 0, 8) == substr(md5(substr($result, 8) . $key), 0, 8)) {
                return substr($result, 8);
            } else {
                return '';
            }
        } else {
            return str_replace('=', '', base64_encode($result));
        }
    }
}

if (! function_exists('get_token')) {
    /**
     * get_token
     * @param string $ua
     * @return string
     */
    function get_token(string $ua)
    {
        $tokenConfig = \app\service\Config::getInstance()->get('token');
        return encrypt($tokenConfig['username'].$tokenConfig['password'],'E',$ua.$tokenConfig['salt']);
    }
}

